/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * <p>Project: mybatis2022 - MybatisConfig
 * <p>Powered by webrx On 2022-04-11 11:07:06
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@Configuration

//加载resources/db.properties 配置文件
@PropertySource("classpath:db.properties")

//扫描有Mapper注解的接口 @Mapper 主要是解决，单元测试时报红
@ComponentScan("cn.webrx.mapper")

//也是扫描包，在接口上可以不加@Mapper
@MapperScan("cn.webrx.mapper")
public class MybatisConfig {
    @Value("${db.driver:com.mysql.cj.jdbc.Driver}")
    private String driver;
    @Value("${db.url:jdbc:mysql:/db}")
    private String url;
    @Value("${db.username:admin}")
    private String username;
    @Value("${db.password:123}")
    private String password;

    @Bean(name = "ds", initMethod = "init", destroyMethod = "close")
    @Primary
    public DruidDataSource ds() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setUrl(url);
        return ds;
    }

    @Bean(name = "sf")
    @Primary
    public SqlSessionFactoryBean sf(DruidDataSource ds) throws IOException {
        SqlSessionFactoryBean sf = new SqlSessionFactoryBean();
        sf.setDataSource(ds);

        // resources/mapper/XxxMapper.xml
        sf.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper*.xml"));
        return sf;
    }
}
